import TextureDisperseAssembler from "./TextureDisperseAssembler";

const { ccclass, menu, property } = cc._decorator;

@ccclass
@menu('TextureDisperse/TextureDisperseRender')
export default class TextureDisperseRender extends cc.RenderComponent {

    /** 纹理 */
    @property()
    private _texture: cc.Texture2D = null;
    @property({ type: cc.Texture2D, tooltip: '纹理' })
    public get texture(): cc.Texture2D {
        return this._texture;
    }
    public set texture(value: cc.Texture2D) {
        this._texture = value;

        this.node.width = this._texture.width;
        this.node.height = this._texture.height;

        this.resetVerts();
    }

    @property()
    _vertXCount: number = 2;
    @property({ step: 1, min: 2, max: 2000, tooltip: '上下边顶点数量(x 方向上)' })
    public get vertXCount() {
        return this._vertXCount;
    }
    public set vertXCount(value) {
        if (this._vertXCount === value) { return; }

        if (!this._vertXCount) this._vertXCount = 2;
        this._vertXCount = value;
        this.resetVerts();
    }

    @property()
    _vertYCount: number = 2;
    @property({ step: 1, min: 2, max: 2000, tooltip: '左右边顶点数量(y 方向上)', })
    public get vertYCount() {
        return this._vertYCount;
    }
    public set vertYCount(value) {
        if (this._vertYCount === value) { return; }

        this._vertYCount = value;
        this.resetVerts();
    }

    protected _initedMaterial: boolean = false;

    onEnable() {
        super.onEnable();
        this.init();

        if (!this._assembler) { return; }
        //@ts-ignore
        this._assembler.updateRenderData(this);
    }

    public init() {
        if (!this._initedMaterial) {
            this.updateMaterial();
        }
        this.setVertsDirty();
    }

    public _resetAssembler() {
        let assembler = this._assembler = new TextureDisperseAssembler();
        assembler.init(this);
    }

    protected _updateMaterial() {
        let material = this.getMaterial(0);
        if (material) {
            material.define('CC_USE_MODEL', 1);
            material.setProperty('texture', this.texture);
        }
    }

    protected updateMaterial() {
        this._updateMaterial();
        this._initedMaterial = true;
    }

    private resetVerts() {
        //@ts-ignore
        this._assembler.updatePoint(this);

        //@ts-ignore
        this._assembler.initData();

        this.init();
        if (!this._assembler) { return; }
        //@ts-ignore
        this._assembler.updateRenderData(this);

        //@ts-ignore
        this._assembler.updateColor(this, null);
    }
}
